<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Bid;
use App\Pro;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;

class BidsController extends Controller
{
    public function touziFrom(Request $req,$id) {
        $pro = Pro::find($id);
        return view('lijitouzi',['pro'=>$pro]);
    }

    public function touziPost(Request $req) {
        $pro = Pro::find($req->id);
        if ($pro->money == $pro->receive ) {
           return '抱歉，投标已满，已经结束投标！';
        }
        $bid= new Bid();
        $money = $req->money*100;

        $bid->title = $req->title;
        $bid->money = intval($money);
        $bid->pid = $req->id;
        $bid->uid = $req->user()->uid;
        $bid->pubtime =time();



        if (($money +  $pro->receive) >$pro->money) {
            return '抱歉，你投标的钱已经超过了招标的最大额度！';
        }
        $res = $bid->save();
        if($res && (($money +  $pro->receive) == $pro->money)) {
            $pro->increment('receive',$money );
            $this->touzi($pro);
            return '恭喜你，你已经投标成功1！';
        }
        if ($res && (($money +  $pro->receive) < $pro->money)) {
            $pro->increment('receive',$money );
            return '恭喜你，你已经投标成功2！';
        }
    }
    public function touzi($pro) {
        //修改项目状态 2 还款中
        $pro->status = 2;
        $pro->save();

        //招标者产生还款记录
        $row = [
            'pid'=> $pro->id,
            'uid'=> $pro->uid,
            'title'=>$pro->title,
            'status'=>0,
        ];

        for($i=1; $i <= $pro->hrange; $i++) {
            $row['amount'] = ($pro->money * $pro->rate / 1200) + ($pro->money / $pro->hrange); //  算出每月还款额
            $row['paytime'] =  date('Y-m-d',strtotime("+ $i months"));
            DB::table('hks')->insert($row);
        }


        //投标人产生收益记录

    }
}
